﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;

namespace Yb
{
    public static class ConfigBinding
    {
        private static Config _config;
        private static readonly bool _enableDebugOutput = true; // 👈 调试时打开，发布时关闭

        public static void Initialize(Config config)
        {
            try
            {
                _config = config;
                DebugWriteLine("ConfigBinding initialized");
            }
            catch (Exception ex)
            {
                DebugWriteLine($"Initialize 失败: {ex.Message}");
            }
        }

        public static void Bind(Control control)
        {
            if (_config == null || control == null || string.IsNullOrWhiteSpace(control.Tag?.ToString()))
                return;

            try
            {
                string tag = control.Tag.ToString();
                string[] parts = tag.Split('|');
                string key = parts.Length > 0 ? parts[0] : "";
                string defaultValue = parts.Length > 1 ? parts[1] : "";
                string listKey = parts.Length > 2 ? parts[2] : "";

                DebugWriteLine($"绑定控件: {control.Name ?? "无名"}, Tag={tag}");

                if (control is TextBox textBox)
                {
                    BindTextBox(textBox, key, defaultValue);
                }
                else if (control is NumericUpDown numericUpDown)
                {
                    BindNumericUpDown(numericUpDown, key, defaultValue);
                }
                else if (control is ComboBox comboBox)
                {
                    BindComboBox(comboBox, key, defaultValue, listKey);
                }
                else if (control is ListBox listBox)
                {
                    BindListBox(listBox, key, defaultValue, listKey);
                }
                else if (control is CheckBox checkBox)
                {
                    BindCheckBox(checkBox, key, defaultValue);
                }
                else
                {
                    DebugWriteLine($"不支持的控件类型: {control.GetType().Name}");
                }
            }
            catch (Exception ex)
            {
                DebugWriteLine($"Bind 控件失败 {control.Name}: {ex.Message}");
            }
        }

        public static void BindAll(Control container)
        {
            try
            {
                if (container == null) return;

                foreach (Control ctrl in container.Controls)
                {
                    Bind(ctrl);
                    if (ctrl?.HasChildren == true)
                    {
                        BindAll(ctrl);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindAll 失败: {ex.Message}");
            }
        }

        #region 控件绑定实现

        private static void BindTextBox(TextBox textBox, string key, string defaultValue)
        {
            try
            {
                string finalValue;

                if (int.TryParse(defaultValue, out int intDefault))
                {
                    finalValue = _config.Get(key, intDefault).ToString();
                }
                else if (double.TryParse(defaultValue, out double doubleDefault))
                {
                    finalValue = _config.Get(key, doubleDefault).ToString();
                }
                else if (bool.TryParse(defaultValue, out bool boolDefault))
                {
                    finalValue = _config.Get(key, boolDefault).ToString();
                }
                else
                {
                    finalValue = _config.Get(key, defaultValue);
                }

                DebugWriteLine($"TextBox [{key}] 设置值: '{finalValue}' (默认: '{defaultValue}')");
                textBox.Text = finalValue;

                textBox.Leave += (s, e) =>
                {
                    try
                    {
                        if (int.TryParse(defaultValue, out _))
                        {
                            if (int.TryParse(textBox.Text, out int val))
                                _config.Set(key, val);
                        }
                        else if (double.TryParse(defaultValue, out _))
                        {
                            if (double.TryParse(textBox.Text, out double val))
                                _config.Set(key, val);
                        }
                        else if (bool.TryParse(defaultValue, out _))
                        {
                            if (bool.TryParse(textBox.Text, out bool val))
                                _config.Set(key, val);
                        }
                        else
                        {
                            _config.Set(key, textBox.Text);
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugWriteLine($"TextBox.Leave 保存失败 Key={key}: {ex.Message}");
                    }
                };
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindTextBox 失败 Key={key}: {ex.Message}");
            }
        }

        private static void BindNumericUpDown(NumericUpDown numericUpDown, string key, string defaultValue)
        {
            try
            {
                decimal finalValue;
                bool isInt = int.TryParse(defaultValue, out int intDefault);
                bool isDecimal = decimal.TryParse(defaultValue, out decimal decDefault);

                if (isInt)
                {
                    finalValue = _config.Get(key, (decimal)intDefault);
                }
                else if (isDecimal)
                {
                    finalValue = _config.Get(key, decDefault);
                }
                else
                {
                    finalValue = _config.Get(key, 0m);
                }

                // 👇 关键：临时放宽范围，确保能设置值
                decimal oldMin = numericUpDown.Minimum;
                decimal oldMax = numericUpDown.Maximum;

                numericUpDown.Minimum = Math.Min(oldMin, finalValue);
                numericUpDown.Maximum = Math.Max(oldMax, finalValue);

                DebugWriteLine($"NumericUpDown [{key}] 设置值: {finalValue} (默认: {defaultValue})");
                numericUpDown.Value = finalValue;

                // 恢复原始范围
                numericUpDown.Minimum = oldMin;
                numericUpDown.Maximum = oldMax;

                numericUpDown.ValueChanged += (s, e) =>
                {
                    try
                    {
                        if (isInt)
                        {
                            _config.Set(key, (int)numericUpDown.Value);
                        }
                        else
                        {
                            _config.Set(key, numericUpDown.Value);
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugWriteLine($"NumericUpDown 保存失败 Key={key}: {ex.Message}");
                    }
                };
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindNumericUpDown 失败 Key={key}: {ex.Message}");
            }
        }

        private static void BindComboBox(ComboBox comboBox, string key, string defaultValue, string listKey)
        {
            try
            {
                // 判断是否已使用 DataSource 绑定（如你手动设置的 qualityOptions）
                bool isDataSourceBound = comboBox.DataSource != null;

                if (isDataSourceBound)
                {
                    // ========== 模式1：DataSource 已绑定（你的当前用法）==========
                    // 此时 listKey 应该忽略（或可选用于验证）
                    // 直接从配置读取值，赋给 SelectedValue

                    string selectedValue = _config.Get(key, defaultValue);
                    DebugWriteLine($"ComboBox [{key}] (DataSource模式) 设置 SelectedValue: '{selectedValue}'");

                    // 尝试设置 SelectedValue（必须是 ValueMember 对应的类型，通常是 string）
                    try
                    {
                        comboBox.SelectedValue = selectedValue;
                    }
                    catch
                    {
                        // 如果值不在列表中，SelectedValue 会抛异常，回退到默认
                        if (!string.IsNullOrEmpty(defaultValue))
                            comboBox.SelectedValue = defaultValue;
                    }

                    // 保存时直接取 SelectedValue
                    comboBox.SelectionChangeCommitted += (s, e) =>
                    {
                        try
                        {
                            var val = comboBox.SelectedValue?.ToString() ?? "";
                            _config.Set(key, val);
                            DebugWriteLine($"ComboBox [{key}] 保存 SelectedValue: '{val}'");
                        }
                        catch (Exception ex)
                        {
                            DebugWriteLine($"ComboBox 保存失败 Key={key}: {ex.Message}");
                        }
                    };
                }
                else
                {
                    // ========== 模式2：传统 Items 模式（原有逻辑）==========
                    if (!string.IsNullOrWhiteSpace(listKey))
                    {
                        var items = _config.GetList<string>(listKey, new List<string>());
                        comboBox.Items.Clear();
                        foreach (var item in items)
                        {
                            comboBox.Items.Add(item);
                        }
                        DebugWriteLine($"ComboBox [{key}] 加载 {items.Count} 项数据源");
                    }

                    string selectedValue = _config.Get(key, defaultValue);
                    DebugWriteLine($"ComboBox [{key}] 设置选中值: '{selectedValue}' (默认: '{defaultValue}')");

                    if (!string.IsNullOrEmpty(selectedValue))
                    {
                        int index = comboBox.FindStringExact(selectedValue);
                        if (index >= 0)
                        {
                            comboBox.SelectedIndex = index;
                        }
                        else
                        {
                            comboBox.Text = selectedValue;
                        }
                    }

                    comboBox.SelectionChangeCommitted += (s, e) =>
                    {
                        try
                        {
                            _config.Set(key, comboBox.Text);
                        }
                        catch (Exception ex)
                        {
                            DebugWriteLine($"ComboBox 保存失败 Key={key}: {ex.Message}");
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindComboBox 失败 Key={key}, ListKey={listKey}: {ex.Message}");
            }
        }

        private static void BindListBox(ListBox listBox, string key, string defaultValue, string listKey)
        {
            try
            {
                // 1. 先加载数据源
                if (!string.IsNullOrWhiteSpace(listKey))
                {
                    var items = _config.GetList<string>(listKey, new List<string>());
                    listBox.Items.Clear();
                    foreach (var item in items)
                    {
                        listBox.Items.Add(item);
                    }
                    DebugWriteLine($"ListBox [{key}] 加载 {items.Count} 项数据源");
                }

                // 2. 再设置选中项
                var selectedItems = _config.GetList<string>(key, new List<string>());
                DebugWriteLine($"ListBox [{key}] 设置选中项: {string.Join(", ", selectedItems)}");

                if (listBox.SelectionMode == SelectionMode.One && selectedItems.Count > 0)
                {
                    string first = selectedItems[0];
                    int index = listBox.Items.IndexOf(first);
                    if (index >= 0)
                    {
                        listBox.SelectedIndex = index;
                    }
                }
                else if (listBox.SelectionMode != SelectionMode.One)
                {
                    listBox.ClearSelected();
                    foreach (string item in selectedItems)
                    {
                        int index = listBox.Items.IndexOf(item);
                        if (index >= 0)
                        {
                            listBox.SetSelected(index, true);
                        }
                    }
                }

                listBox.SelectedIndexChanged += (s, e) =>
                {
                    try
                    {
                        if (listBox.SelectionMode == SelectionMode.One)
                        {
                            if (listBox.SelectedItem != null)
                            {
                                _config.Set(key, listBox.SelectedItem.ToString());
                            }
                        }
                        else
                        {
                            var selected = new List<string>();
                            foreach (object item in listBox.SelectedItems)
                            {
                                selected.Add(item.ToString());
                            }
                            _config.SetList(key, selected);
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugWriteLine($"ListBox 保存失败 Key={key}: {ex.Message}");
                    }
                };
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindListBox 失败 Key={key}, ListKey={listKey}: {ex.Message}");
            }
        }

        private static void BindCheckBox(CheckBox checkBox, string key, string defaultValue)
        {
            try
            {
                bool defaultVal = false;
                if (bool.TryParse(defaultValue, out bool parsed))
                {
                    defaultVal = parsed;
                }

                bool isChecked = _config.Get(key, defaultVal);
                DebugWriteLine($"CheckBox [{key}] 设置值: {isChecked} (默认: {defaultVal})");
                checkBox.Checked = isChecked;

                checkBox.CheckedChanged += (s, e) =>
                {
                    try
                    {
                        _config.Set(key, checkBox.Checked);
                    }
                    catch (Exception ex)
                    {
                        DebugWriteLine($"CheckBox 保存失败 Key={key}: {ex.Message}");
                    }
                };
            }
            catch (Exception ex)
            {
                DebugWriteLine($"BindCheckBox 失败 Key={key}: {ex.Message}");
            }
        }

        #endregion

        private static void DebugWriteLine(string message)
        {
            if (_enableDebugOutput)
            {
                try
                {
                    System.Diagnostics.Debug.WriteLine($"[Yb.ConfigBinding] {message}");
                }
                catch { }
            }
        }
    }
}